import cv2

# device代表调用的摄像头
def enDetect(device):
    global roi_gray, roi_color, h_eye, center, nose_rects
    id = input("请输入采集对象的序号：")

    # 加载xml文件生成分类器
    face_casecade = cv2.CascadeClassifier('D:/facere/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
    eye_casecade = cv2.CascadeClassifier('D:/facere/venv/Lib/site-packages/cv2/data/haarcascade_eye.xml')
    nose_casecade = cv2.CascadeClassifier('D:/facere/venv/Lib/site-packages/cv2/data/haarcascade_mcs_nose.xml')

    # img = cv2.imread(filename) -> 摄像头获取
    cap = cv2.VideoCapture(device) # 电脑摄像头

    while cap.isOpened():
        ret,frame = cap.read()
        # 使用INTER_AREA插值法把图像的宽和高缩小为原来的一半
        frame = cv2.resize(frame, None, fx = 0.5, fy=0.5, interpolation=cv2.INTER_AREA)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)   #转换成灰度文件

        # scaleFactor:图像缩小的比例
        face_rects = face_casecade.detectMultiScale(gray,1.1, minNeighbors=5)

        # 用矩形框出每张人脸

        for(x,y,w,h) in face_rects:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)  # 蓝色框（B=255，G=R=0）
            roi_gray = gray[y:y+h, x:x+w]    # 提取人脸区域
            roi_color = frame[y:y+h, x:+w]   # 视频中人脸区域图像
            eye_rects = eye_casecade.detectMultiScale(roi_gray)
            nose_rects = nose_casecade.detectMultiScale(roi_gray, 1.3, 5)
            for(x_eye, y_eye, w_eye, h_eye) in eye_rects:
                center = (int(x_eye + 0.5*w_eye), int(y_eye + 0.5*h_eye))
                radius = int(0.3 * (w_eye + h_eye))
                cv2.circle(roi_color, center, radius, (0, 255, 0), 4)     # 用绿色圆框标记眼睛
            for(x_nose, y_nose, w_nose, h_nose) in nose_rects:
                cv2.rectangle(roi_color, (x_nose, y_nose), (x_nose+w_nose, y_nose+h_nose), (0, 0, 255), 2)      # 用红色框标记鼻子
                break

        cv2.imshow('Eye and nose Detector', frame)
        k = cv2.waitKey(1)

        if k == ord('s') or k == ord('S'):
            save_path = 'C:/Users/shouw/Desktop/tmp/eyenosedesou/'
            cv2.imwrite(save_path + 'en' + str(id) + '.jpg', frame)
            break
        elif k & 0xff == ord('q') or k & 0xff == ord('Q'):
            break
    cap.release()
    cv2.destroyAllWindows()
enDetect(0)